<?php
namespace Common\Behaviors;
class wxLoginBehavior extends \Think\Behavior
{
    //行为执行入口
    public function run(&$param)
    {
        $this->user_id = session("user_id");
        $user_info = BoxModel("system_member")->load($this->user_id);
        if ($user_info['user_id']) {                //已经登录
            return true;
        }
        if (checkAgent()) {        //非微信浏览器
            return true;
        }
        //$this->store_id=getStoreID();
        $this->store_id = I('store_id', "1", "intval");
        $this->storeInfo = BoxModel("addon_wx_config")->load($this->store_id);
        $param = array(
            'token' => $this->storeInfo['token'],
            'appID' => $this->storeInfo['appID'],
            'appsecret' => $this->storeInfo['appsecret'],
        );
        $this->wechatObj = new \Common\Org\weiXin($param);
        $code = I('code');
        if ($code) {
            $this->OAuthLogin($code);
        } else {
            $this->getCode();
        }

    }

    protected function getCode()
    {
        $this->appID = $this->storeInfo['appID'];
        $scope = I('scope', "snsapi_base");
        $backUl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        /********登录成功之后跳转******/
        $bool = strpos($backUl, "?");
        $backUl = $bool === false ? ($backUl . "?backUrl=" . I('backUrl')) : ($backUl . "&backUrl=" . I('backUrl'));
        $backUl = urlencode($backUl);
        //$backUl=I('backUrl',$backUl); //登录之后回调地址
        /*******如果在微信中浏览直接使用微信同步登录*********/
        $scope = $scope ? $scope : "snsapi_base";
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appID}&redirect_uri={$backUl}&response_type=code&scope={$scope}&state=123#wechat_redirect";
        header("location:$url");
    }

    /*******微信自动登录,授权后返回Code登录*******/
    protected function OAuthLogin($code)
    {
        $data = $this->wechatObj->OAuthUserInfo($code);
        if (!($openid = $data['openid'])) {
            $this->jumpToUrl();
        }
        //网页授权登录
        if ($data['scope'] == "snsapi_userinfo") {
            $user_info = $this->wechatObj->UserInfoBySnsapi($openid, $data['access_token']);
        } else {
            $user_info = $this->wechatObj->UserInfo($openid);
        }

        $where = array(
            'type_uid' => $user_info['openid'],
            'type' => 'weixin',
        );
        $sync_login = BoxModel("system_member")->where(array('openid' => $user_info['openid']))->find();
        if ($user_id = $sync_login['user_id']) {
            Logic("BoxSns", "Member")->saveLogin($user_id);
        } elseif (is_array($user_info)) {
            $user_id = Logic("BoxSns", "Member")->WxCreateMember($user_info);
            Logic("BoxSns", "Member")->saveLogin($user_id);
        }
        /******单点登录****/
        $user_info = BoxModel("SystemMember")->load($user_id);
        $r = Logic("BoxSns", "Member")->do_login($user_info['user_name'], $user_info['password'],1);
        $this->jumpToUrl();
    }

    /*********微信登录成功，或失败****/
    function jumpToUrl()
    {
        $backUl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $backUl = preg_replace('/(&|\?)code=[^&]+/', '', $backUl);
        header("location:$backUl");
        exit();
    }
}
